﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ePlanet.ArchiveBorrow.DataAccess;
using ePlanet.ArchiveBorrow.Models;
using ePlanet.ArchiveBorrow.Services;
using DreamBuilder.Common;
using Web.SystemConfig.WorkFlow;

namespace ePlanet.ArchiveBorrow.Business
{
    public class BUSArchiveBorrow : BusinessBase, IArchiveBorrowService
    {
        private ArchiveBorrowDAL m_ArchiveBorrowDAL = null;
        public BUSArchiveBorrow()
        {
            if (this.m_ArchiveBorrowDAL == null)
            {
                this.m_ArchiveBorrowDAL = new ArchiveBorrowDAL();
            }
        }

        /// <summary>
        /// 新建档案借阅记录
        /// </summary>
        /// <param name="model"></param>
        public void InsertNewArchiveBorrowModel(ArchiveBorrowModel model)
        {
            this.m_ArchiveBorrowDAL.InsertNewArchiveBorrowModel(model);
        }

        /// <summary>
        /// 更新档案借阅记录
        /// </summary>
        /// <param name="model"></param>
        public void UpdateArchiveBorrowModel(ArchiveBorrowModel model)
        {
            this.m_ArchiveBorrowDAL.UpdateArchiveBorrowModel(model);
        }

        /// <summary>
        /// 获取单个档案借阅记录
        /// </summary>
        /// <param name="dataID"></param>
        /// <returns></returns>
        public ArchiveBorrowModel GetSingleArchiveBorrowModelByDataID(Guid dataID)
        {
            return this.m_ArchiveBorrowDAL.GetSingleArchiveBorrowModelByDataID(dataID);
        }

        /// <summary>
        /// 通过用户获取该用户所有的记录
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="beginNum"></param>
        /// <param name="count"></param>
        /// <param name="sum"></param>
        /// <returns></returns>
        public ArchiveBorrowModel GetArchiveBorrowModelListByUserID(Guid userID, int statusID, int beginNum, int count, out int sum)
        {
            return this.m_ArchiveBorrowDAL.GetArchiveBorrowModelListByUserID(userID, statusID, beginNum, count, out sum);
        }

        /// <summary>
        /// 通过档案类型获取所有的记录
        /// </summary>
        /// <param name="achiveType"></param>
        /// <param name="beginNum"></param>
        /// <param name="count"></param>
        /// <param name="sum"></param>
        /// <returns></returns>
        public ArchiveBorrowModel GetArchiveBorrowModelListByArchiveType(string achiveType, int statusID, int beginNum, int count, out int sum)
        {
            return this.m_ArchiveBorrowDAL.GetArchiveBorrowModelListByArchiveType(achiveType, statusID, beginNum, count, out sum);
        }

        /// <summary>
        /// 获取部门形成单位领导
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public DataTable GetToUserList(int roleID)
        {
            DataTable rtnList = null;
            DataTable oDataTable = this.m_ArchiveBorrowDAL.GetToUserList(roleID);
            if (oDataTable != null && oDataTable.Rows.Count > 0)
            {
                rtnList = oDataTable;
            }
            return rtnList;
        }

        /// <summary>
        /// 获取待办数据
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="beginNum"></param>
        /// <param name="count"></param>
        /// <param name="sum"></param>
        /// <returns></returns>
        public ArchiveBorrowModel GetAgent(string userID, int beginNum, int count, string filter, ref int sum)
        {
            return this.m_ArchiveBorrowDAL.GetAgent(userID, beginNum, count, filter, ref sum);
        }

        /// <summary>
        /// 获取已办数据
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="beginNum"></param>
        /// <param name="count"></param>
        /// <param name="sum"></param>
        /// <returns></returns>
        public ArchiveBorrowModel GetDone(string userID, int beginNum, int count, string filter, ref int sum)
        {
            return this.m_ArchiveBorrowDAL.GetDone(userID, beginNum, count, filter, ref sum);
        }

        /// <summary>
        /// 创建新OrderID
        /// </summary>
        /// <param name="newOrderID"></param>
        /// <returns></returns>
        public bool GetNewOrderID(out string newOrderID)
        {
            bool rtnBool = false;
            newOrderID = string.Empty;
            uint maxValue = uint.MinValue;
            string rtnString = this.m_ArchiveBorrowDAL.GetMaxOrderID(out maxValue);
            if (string.IsNullOrEmpty(rtnString))
            {
                maxValue = maxValue + 1;
                int len = maxValue.ToString().Length;
                if (len < 8)
                {
                    newOrderID = "00000000".Substring(0, 8 - len) + maxValue.ToString();
                    rtnBool = true;
                }
            }

            return rtnBool;
        }


        public ArchiveBorrowModel GetTotale(string userID, int beginNum, int count, out int sum)
        {
            sum = 0;
            return this.m_ArchiveBorrowDAL.GetTotal(userID, beginNum, count, out sum);
        }

        public ArchiveBorrowModel GetHasLend(string userID, int beginNum, int count, out int sum)
        {
            sum = 0;
            return this.m_ArchiveBorrowDAL.GetHasLend(userID, beginNum, count, out sum);
        }

        public ArchiveBorrowModel GetHasReturn(string userID, int beginNum, int count, out int sum)
        {
            sum = 0;
            return this.m_ArchiveBorrowDAL.GetHasReturn(userID, beginNum, count, out sum);
        }

        public ArchiveBorrowModel GetFaild(string userID, int beginNum, int count, ref int sum)
        {
            return this.m_ArchiveBorrowDAL.GetFaild(userID, beginNum, count, ref sum);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataID"></param>
        /// <returns></returns>
        public List<ArchiveBorrowModel> GetArchiveBorrowOrderData(string dataID)
        {
            List<ArchiveBorrowModel> rtnArchiveBorrowModel = null;
            List<string> result = new List<string>();
            //获取相同OrderID的所有数据和操作日志
            DataTable data = this.m_ArchiveBorrowDAL.GetSameOrderIDData(dataID);
            DataTable dataOperateLog = this.m_ArchiveBorrowDAL.GetSameOrderIDDataOperateLog(dataID);
            //获取当前数据的操作日志
            DataRow[] currentDataLog = dataOperateLog.Select(string.Format("RecordID='{0}'", dataID));
            ///分析当前日志操作日志
            if (currentDataLog.Count(row => row["OperateID"].ToString() == "1003") > 0)
            {
                //是否管理员同意借阅
                foreach (DataRow row in data.Rows)
                {
                    //选择遍历的数据的操作日志
                    DataRow[] logDataRowArr = dataOperateLog.Select(string.Format("RecordID='{0}'", row["DataID"].ToString()));
                    if (logDataRowArr.Count(logrow => logrow["OperateID"].ToString() == "1003") > 0)
                    {
                        result.Add(row["DataID"].ToString());
                    }
                }
            }
            else if (currentDataLog.Count(row => row["OperateID"].ToString() == "1009") > 0)
            {
                //信息中心领导审核通过，需要判断档案形成部门领导
                string ncDAXCBMLD = string.Empty;
                string wcDAXCBMLD = string.Empty;
                string ncDAXCBM = string.Empty;
                string wcDAXCBM = string.Empty;

                foreach (DataRow dr in currentDataLog)
                {
                    //送档案形成部门操作
                    //内厂
                    if (dr["OperateID"].ToString() == "1005" && dr["SignUserID"] != null && dr["SignUserID"] != DBNull.Value)
                    {
                        ncDAXCBMLD = dr["SignUserID"].ToString();
                        ncDAXCBM = this.m_ArchiveBorrowDAL.GetUserOrgID(ncDAXCBMLD);
                        break;
                    }
                    //外厂
                    if (dr["OperateID"].ToString() == "1011" && dr["SignUserID"] != null && dr["SignUserID"] != DBNull.Value)
                    {
                        wcDAXCBMLD = dr["SignUserID"].ToString();
                        wcDAXCBM = this.m_ArchiveBorrowDAL.GetUserOrgID(wcDAXCBMLD);
                        break;
                    }
                }

                foreach (DataRow row in data.Rows)
                {
                    DataRow[] logDataRowArr = dataOperateLog.Select(string.Format("RecordID='{0}'", row["DataID"].ToString()));
                    if (logDataRowArr.Count(r => r["OperateID"].ToString() == "1009") > 0)
                    {
                        if (!string.IsNullOrEmpty(ncDAXCBMLD))
                        {
                            if (logDataRowArr.Count(logrow => logrow["OperateID"].ToString() == "1005" && logrow["SignUserID"] != null && logrow["SignUserID"] != DBNull.Value) > 0)
                            {
                                foreach (DataRow dr in logDataRowArr)
                                {
                                    if (dr["SignUserID"] != null && dr["SignUserID"] != DBNull.Value && this.m_ArchiveBorrowDAL.GetUserOrgID(dr["SignUserID"].ToString()) == ncDAXCBM)
                                    {
                                        result.Add(row["DataID"].ToString());
                                        break;
                                    }
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(wcDAXCBMLD))
                        {
                            if (logDataRowArr.Count(logrow => logrow["OperateID"].ToString() == "1011" && logrow["SignUserID"] != null && logrow["SignUserID"] != DBNull.Value) > 0)
                            {
                                foreach (DataRow dr in logDataRowArr)
                                {
                                    if (dr["SignUserID"] != null && dr["SignUserID"] != DBNull.Value && this.m_ArchiveBorrowDAL.GetUserOrgID(dr["SignUserID"].ToString()) == wcDAXCBM)
                                    {
                                        result.Add(row["DataID"].ToString());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (currentDataLog.Count(row => row["OperateID"].ToString() == "1014") > 0)
            {
                result.Add(dataID);
            }

            if (result != null && result.Count > 0)
            {
                rtnArchiveBorrowModel = new List<ArchiveBorrowModel>();
                ArchiveBorrowModel model = new ArchiveBorrowModel();
                model.ARCHIVEBORROW.Merge(data);

                for (int index = 0; index < model.ARCHIVEBORROW.Rows.Count; index++)
                {
                    if (!result.Contains(model.ARCHIVEBORROW.Rows[index]["DataID"].ToString()))
                    {
                        model.ARCHIVEBORROW.Rows.Remove(model.ARCHIVEBORROW.Rows[index]);
                        index--;
                    }
                }

                rtnArchiveBorrowModel.Add(model);
            }

            return rtnArchiveBorrowModel;
        }

        /// <summary>
        /// 是否全部完成
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public bool IsAllFinish(string dataID)
        {
            ArchiveBorrowModel model = this.GetSingleArchiveBorrowModelByDataID(new Guid(dataID));
            if (!(model == null || string.IsNullOrEmpty(model.ARCHIVEBORROW[0].ORDERID)))
            {
                return this.m_ArchiveBorrowDAL.IsAllFinish(model.ARCHIVEBORROW[0].ORDERID);
            }
            else
            {
                throw new Exception("当前数据不存在");
            }
        }


        public void PaperArchiveLend(string archiveDataID, DateTime rerutntime)
        {
            this.m_ArchiveBorrowDAL.PaperArchiveLend(archiveDataID, rerutntime);
        }

        public void PaperArchiveReturn(string archiveDataID)
        {
            this.m_ArchiveBorrowDAL.PaperArchiveReturn(archiveDataID);
        }


        public List<ArchiveBorrowMenuItem> GetAllArchiveBorrowMenu()
        {
            var result = this.m_ArchiveBorrowDAL.QueryAllArchiveBorrowMenu();
            if (result != null && result.Rows.Count > 0)
            {
                var rtnList = new List<ArchiveBorrowMenuItem>();
                foreach (DataRow row in result.Rows)
                {
                    rtnList.Add(new ArchiveBorrowMenuItem()
                    {
                        TypeID = int.Parse(row["TypeID"].ToString()),
                        ArchiveMenu = row["ArchiveMenu"].ToString(),
                        ParentID = int.Parse(row["ParentID"].ToString()),
                        TypeCode = row["TypeCode"].ToString()
                    });
                }

                return rtnList;
            }

            return null;
        }


        public Dictionary<string, int> GetrchiveBorrowStatistics(DateTime beginTime, DateTime endTime, int archiveType)
        {
            var rtnList = new Dictionary<string, int>();
            var result = m_ArchiveBorrowDAL.GetArvhiceBorrowStatistics(beginTime, endTime, archiveType);
            if (result == null || result.Rows.Count != 5)
                return null;

            rtnList.Add("PeopleCount", Convert.ToInt32(result.Rows[0][0]));
            rtnList.Add("ArchiveCount", Convert.ToInt32(result.Rows[1][0]));
            rtnList.Add("PaperCount", Convert.ToInt32(result.Rows[2][0]));
            rtnList.Add("PaperLendCount", Convert.ToInt32(result.Rows[3][0]));
            rtnList.Add("PaperReturnCount", Convert.ToInt32(result.Rows[4][0]));

            return rtnList;
        }
    }
}
